//
//  KRAlbumListController.m
//  cookBook
//
//  Created by kuroken on 16/1/14.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRAlbumListController.h"
#import "KRConst.h"
#import "KRAlbumListCell.h"
#import "KRAlbumList.h"
#import "KRHttpRecipeTool.h"
#import <MJExtension.h>
#import <SVProgressHUD.h>
#import <MJRefresh.h>
#import "KRAlbumInfoController.h"
#import "KRNoNetCell.h"

@interface KRAlbumListController () <UINavigationControllerDelegate>
/** 专辑模型数组 */
@property (nonatomic, strong) NSMutableArray<KRAlbumList *> *albumList;
@property (nonatomic, assign) NSUInteger offset;
/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDataTask;
@property (nonatomic, assign, getter=isError) BOOL error;
@end

@implementation KRAlbumListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [[UIView alloc] init];

    /* 加载数据 */
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.albumList) {
        // 显示指示器
        [SVProgressHUD show];
#warning iOS7 SVProgressHUD写在viewDidLoad，不转圈
        self.tableView.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.currentDataTask cancel];
    self.currentDataTask = nil;
    [SVProgressHUD dismiss];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

/**
 *  加载更多数据
 */

- (void)loadMoreData
{
    KRLog(@"从第%d个专辑开始加载", (int)self.offset);
    
    if (_currentDataTask) {
        [self.currentDataTask cancel];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
    }

    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRRecipeetAlbumList;
        requestParams[@"limit"] = @"10";
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];

    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;

        self.offset += 10;
        NSArray *newAlbumList = [KRAlbumList mj_objectArrayWithKeyValuesArray:json[@"result"][@"list"]];
        if (newAlbumList.count == 0) {
            [SVProgressHUD showInfoWithStatus:@"已无更多数据"];
        }
        [self.albumList addObjectsFromArray:newAlbumList];
        [self.tableView reloadData];
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙！"];
        });
        
        KRLog(@"%@, %@", self, error);
    }];
}

/**
 *  加载数据
 */
- (void)loadData
{
    if (!self.albumList) {
        // 显示指示器
        [SVProgressHUD show];
        self.tableView.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
    }
    
    if (_currentDataTask) {
        [self.currentDataTask cancel];
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }
    
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRRecipeetAlbumList;
        requestParams[@"limit"] = @"10";
//        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];
        requestParams[@"offset"] = @"0";
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;
        
        if (!self.albumList) {
            // 下拉刷新控件
            self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
            
            // 上拉刷新控件
            self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
            
            self.error = NO;
            self.tableView.scrollEnabled = YES;

        }
        self.offset = 0;
        self.albumList = [KRAlbumList mj_objectArrayWithKeyValuesArray:json[@"result"][@"list"]];
        self.offset += self.albumList.count;
        
        [self.tableView reloadData];
        
        // 移除指示器
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
        
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
            [SVProgressHUD showSuccessWithStatus:@"当前已是最新数据"];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        if (!self.albumList) {
            self.error = YES;
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            self.tableView.userInteractionEnabled = YES;
        }
        
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙！"];
        });
        
        KRLog(@"%@, %@", self, error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isError) return 1; // 请求失败
    return self.albumList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"请求超时"];
        return cell;
    }
   
    KRAlbumListCell *cell = [KRAlbumListCell cellWithTableView:tableView];
    cell.albumList = self.albumList[indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;
    
    return baseCellHeight + cellPadding * 2; // 上下各加10的间距
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
        [self loadData];
        return;
    }
    
    KRAlbumInfoController *infoVc = [[KRAlbumInfoController alloc] init];
    
    KRAlbumList *albumList = self.albumList[indexPath.row];
    infoVc.albumID = albumList.ID; //专辑ID
    [self.navigationController pushViewController:infoVc animated:YES];
}

@end